package model

import (
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type FriendLink struct {
	Model
	Name    string `gorm:"type:varchar(50)" json:"name"`
	Avatar  string `gorm:"type:varchar(255)" json:"avatar"`
	Address string `gorm:"type:varchar(255)" json:"address"`
	Intro   string `gorm:"type:varchar(255)" json:"intro"`
}

func GetLinkList(db *gorm.DB, page, size int, keyword string) (list []FriendLink, total int64, err error) {
	// 使用一个新的DB实例，防止原始D被修改
	db = db.Model(&FriendLink{})
	if keyword != "" {
		//db = db.Where("name LIKE ?", "%"+keyword+"%")
		//db = db.Or("address LIKE ?", "%"+keyword+"%")
		//db = db.Or("intro LIKE ?", "%"+keyword+"%")

		db = db.Where(db.Clauses(clause.Where{Exprs: []clause.Expression{gorm.Expr("name LIKE ?", "%"+keyword+"%"), gorm.Expr("OR address LIKE ?", "%"+keyword+"%"), gorm.Expr("OR intro LIKE ?", "%"+keyword+"%")}}))
	}
	err = db.Count(&total).Error // 检查Count操作的错误
	if err != nil {
		return nil, 0, err
	}
	result := db.Order("created_at DESC").Scopes(Paginate(page, size)).Find(&list)
	return list, total, result.Error
}

func SaveOrUpdateLink(db *gorm.DB, id int, name, avatar, address, intro string) (*FriendLink, error) {
	link := FriendLink{Model: Model{ID: id}, Address: address, Name: name, Avatar: avatar, Intro: intro}

	var result *gorm.DB
	if id > 0 {
		result = db.Updates(&link)
	} else {
		result = db.Create(&link)
	}
	return &link, result.Error
}
